<script
	lang="ts"
	setup
>
import { productApplyImportantLevelPut } from '@/api'
import EmptyModal from '@/components/EmptyModal.vue'
import type { IProductApplyImportantLevelPut } from '@/typed/request'
import { type FormInst, type FormRules } from 'naive-ui'
import { computed, onMounted, ref, watch } from 'vue'

interface IProps {
	show: boolean;
	data?: any;
	width?: number | string;
}

const formRef = ref<FormInst | null>(null)
const emit = defineEmits(['update:show', 'update:list'])
const props = withDefaults(defineProps<IProps>(), {
	width: 500
})
const initForm: IProductApplyImportantLevelPut = {
    id:props.data.id,
    importantLevel: null,
	remark: '',
};

const importantLevelList = [
    {label: '⭐', value: 1},
    {label: '⭐⭐', value: 2},
    {label: '⭐⭐⭐', value: 3},
    {label: '⭐⭐⭐⭐', value: 4},
    {label: '⭐⭐⭐⭐⭐', value: 5}
]

const loading = ref(false)
const modalForm = ref<IProductApplyImportantLevelPut>({ ...initForm })
const modalTitle = computed(() => {
	return '重要等级'
})

const rules: FormRules = {
    importantLevel: [{
		required: true,
        type: 'number',
		message: '请输入选择等级',
		trigger: ['change', 'blur']
    }]
}

watch(() => props.data, () => {
    if (props.data) {
        modalForm.value = {
            ...props.data,
        }
    } else {
        modalForm.value = { ...initForm };
    }
})


async function onAdd() {
	formRef.value?.validate(async (errors) => {
		if (!errors) {
			loading.value = true
			const { code } = await productApplyImportantLevelPut(modalForm.value as IProductApplyImportantLevelPut)
			loading.value = false
			if (code === 200) {
				window.$message.success('保存成功')
				modalForm.value = { ...initForm }

				emit('update:list')
				emit('update:show', false)
			}
		}
	})
}

function onCancel() {
	if (!loading.value) {
		emit('update:show', false)
		modalForm.value = { ...initForm }
	}
}



</script>

<template>
	<EmptyModal
		:show="show"
		:width="600"
		:title="modalTitle"
		@confirm="onAdd"
		:on-negative-click="onCancel"
		:on-close="onCancel"
		:on-positive-click="onAdd"
		:positive-button-props="{ loading }"
	>
		<n-form
			ref="formRef"
			:model="modalForm"
			label-placement="left"
			label-width="140"
			:rules="rules"
		>

			<n-form-item label="等级" path="importantLevel">
				<div style="display: flex; align-items: center; gap: 8px;">
					<!-- 给下拉框一个固定或相对宽度 -->
					<n-select
							v-model:value="modalForm.importantLevel"
							:options="importantLevelList"
							placeholder="请选择等级"
							clearable
							style="width: 403px"
					/>
				</div>
			</n-form-item>

			<n-form-item
				label="备注"
				path="remark"
			>
				<n-input
					type="textarea"
					placeholder="请输入备注信息"
					v-model:value="modalForm.remark"
				/>
			</n-form-item>
		</n-form>
	</EmptyModal>
</template>

<style
	lang="less"
	scoped
>
.n-upload {
	width: fit-content;
}
</style>
